package me.pinion.model.book;

import com.jfinal.plugin.activerecord.Db;
import me.pinion.kit.DateKit;
import me.pinion.model.XModel;
import me.pinion.model.annotation.TableBind;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

@TableBind(table = "chapter")
public class Chapter extends XModel<Chapter> {
    public static Chapter dao = new Chapter();

    public String text;
    public Chapter next;

    public Book getBook() {
        return Book.dao.findById(this.getInt("book_id"));
    }

    public String getTitle() {
        return this.getStr("title");
    }

    public String getTextFromDB() {
        if (this.text == null) {
            this.text = this.getStr("text");
        }
        if (this.text == null) {
            this.text = Db.findFirst("SELECT ch.text AS text FROM chapter AS ch WHERE ch.id=?", this.getId()).getStr("text");
        }
        return this.text;
    }

    public Chapter setText(String text) {
        this.text = text;
        return this.set("text", text
                .replaceAll("style=\"(.[^\"]*)\"", "")
                .replaceAll("width=\"(.[^\"]*)\"", "")
                .replaceAll("height=\"(.[^\"]*)\"", ""));
    }

    public String getText() {
        return this.getTextFromDB()
                .replaceAll("style=\"(.[^\"]*)\"", "")
                .replaceAll("width=\"(.[^\"]*)\"", "")
                .replaceAll("height=\"(.[^\"]*)\"", "");
    }

    public Chapter next(){
        if (this.next == null){
            this.next = Chapter.dao.findFirst("SELECT ch.id, ch.title FROM chapter AS ch WHERE ch.book_id=? AND ch.id>?", this.getBook().getId(), this.getId());
        }
        return this.next;
    }

    public boolean hasNext(){
        return this.next() != null;
    }

    public String getFirstParagraph() {
        Document doc = Jsoup.parseBodyFragment(getTextFromDB());
        Element body = doc.body();
        String tempText = body.text();
        return body.text().substring(0, tempText.length() > 140 ? 140 : tempText.length());
    }

    public String getLastUpdateString() {
        return DateKit.toStr(this.getTimestamp("last_update"), "YY-MM-dd");
    }
}
